import cv2

# 读取图片
img = cv2.imread('1.jpg')

# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 二值化处理
ret, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
cv2.imshow('Result', thresh)


# cv2.waitKey(0)

# 查找轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print(type(contours))
print(contours)
list = []
# 遍历轮廓
for cnt in contours:
    # 计算轮廓面积
    area = cv2.contourArea(cnt)
    # 如果面积小于10，则认为是噪音，忽略
    if area < 10:
        continue
    # print(area)


    # 计算轮廓中心
    M = cv2.moments(cnt)
    cx = int(M['m10']/M['m00'])
    cy = int(M['m01']/M['m00'])
    list.append((cx,cy))

    # 在图像中绘制圆形标记
    cv2.circle(img, (cx, cy), 15, (0, 225, 0), 2)
print(len(list))
# 显示结果
cv2.imshow('Result', img)
cv2.imwrite('Result.jpg', img)
# cv2.waitKey(0)
cv2.destroyAllWindows()
